package yxy.game.pm2.active.command.sdk.weixin.onlinegift;

import yxy.apple.logger.Logger;
import yxy.cherry.data.bean.actzaixianfenxiang;
import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.active.module.actdata.ActDataCenter;
import yxy.game.pm2.active.module.sdk.weixin.ActiveModule_在线礼包;
import yxy.game.pm2.bean.Currency;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.PackageMessage;
import yxy.game.pm2.message.SdkActiveMessage;
import yxy.game.pm2.message.SdkActiveMessage.WeiXinOnlineInfoRequest;
import yxy.game.pm2.module.CurrencyHandle;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;

/**
 * 在线礼包
 * @author Dell
 *
 */
@MessageType(proto = Command.WeiXinOnlineInfo, classtype = SdkActiveMessage.WeiXinOnlineInfoRequest.class)
public class CMD_Active_在线礼包_Info extends Command<WeiXinOnlineInfoRequest> {
	
	private static final Logger logger = Logger.create(CMD_Active_在线礼包_Info.class);
	
	@Override
	public void execute(MessageSource messageSource, WeiXinOnlineInfoRequest request) throws Exception {
		String pcode = messageSource.getTag();
		SdkActiveMessage.WeiXinOnlineInfoResponse.Builder response = SdkActiveMessage.WeiXinOnlineInfoResponse.newBuilder();
		
		ActiveModule_在线礼包 am = ActiveModule_在线礼包.get(pcode);
		if(am == null) {
			send(messageSource, response, Result.ActNoOpen);
			return;
		}
				
		am.updatedot();
		
		response.setDrawtime(am.getDraw().getMillis());
		response.addAllGetids(am.getDrawids());
		
		ArrayList<Integer> ids = new ArrayList<Integer>();
		Map<String, actzaixianfenxiang> datamap = ActDataCenter.getAllData(actzaixianfenxiang.class, pcode);
		if(datamap.size() == am.getDrawids().size()) {
			send(messageSource, response, Result.ActHadGet);
			return;
		}
		
		for(actzaixianfenxiang data : datamap.values()) {
			ids.add(data.getId());
		}
		
		int id = 0;
		
		if(am.getDrawids().size() == 0) {
			//未领取过	
			id = Collections.min(ids);
		}else {
			id = Collections.max(am.getDrawids()) + 1;
		}
		
		actzaixianfenxiang data = datamap.get(String.valueOf(id));
		Collection<Currency> curs = Currency.create(data.getRewardtype(), data.getRewardid(), data.getRewardnum());
		Collection<PackageMessage.Item> items = new CurrencyHandle().packItems(curs);
		response.addAllCur(items);
		
		int second = data.getCondition();
		long nextneed = second * 1000 - am.getOnline();
		nextneed = nextneed < 0 ? 0 : nextneed;
		
		response.setNextdrawtime(nextneed);
		
		send(messageSource, response, Result.Success);
	}

	private void send(MessageSource messageSource, SdkActiveMessage.WeiXinOnlineInfoResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}

}
